package com.bawei.mall.product.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.bawei.mall.product.domain.*;
import com.bawei.mall.product.domain.detail.SkuStock;
import com.bawei.mall.product.domain.reponse.MallProductCarInfoResponse;
import com.bawei.mall.product.domain.reponse.ProductGoodsResponse;
import com.bawei.mall.product.domain.request.GenerateOrderRequest;
import com.bawei.mall.product.mapper.MallProductGoodsInfoMapper;
import com.bawei.mall.product.service.IMallProductInfoService;
import com.bawei.mall.product.service.MallProductGoodsInfoService;
import com.bawei.system.domain.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：韩丹阳
 * @Package：com.bawei.mall.product.service.impl
 * @Project：mall_cloud
 * @name：MallProductGoodsInfoServiceImpl
 * @Date：2024/7/9 上午 11:57
 */
@Service
public class MallProductGoodsInfoServiceImpl implements MallProductGoodsInfoService {

    @Autowired
    private MallProductGoodsInfoMapper mallProductGoodsInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MallProductInfoServiceImpl mallProductInfoService;


    @Override
    public ProductGoodsResponse generateConfirmOrder(Integer[] ids) {
        User user = getInfo();
        ProductGoodsResponse productGoodsResponse = new ProductGoodsResponse();
        ArrayList<MallProductGoodsInfo> mallProductCarInfoResponses1 = new ArrayList<>();
        List<MallProductGoodsInfo> mallProductGoodsInfoList = mallProductGoodsInfoMapper.findCarList(ids);
        List<SkuStock> skuStockList = mallProductInfoService.getSkuStockList();
        for (MallProductGoodsInfo mallProductGoodsInfo : mallProductGoodsInfoList) {
            for (SkuStock skuStock : skuStockList) {
                if (skuStock.getId().equals(mallProductGoodsInfo.getProductSkuId())){
                    mallProductGoodsInfo.setProductAttr(skuStock.getSpData());
                }
            }
            mallProductGoodsInfo.setPromotionMessage("每满1000减200");
            mallProductCarInfoResponses1.add(mallProductGoodsInfo);

            // 金额
            CalcAmount calcAmount = new CalcAmount();

            // 总价
            BigDecimal price = BigDecimal.ZERO;
            // 遍历所有商品，计算总价
            for (MallProductGoodsInfo goodsInfo : mallProductCarInfoResponses1) {
                price = price.add(goodsInfo.getPrice().multiply(BigDecimal.valueOf(goodsInfo.getQuantity())));
            }
            // 设置总价
            calcAmount.setTotalAmount(price);

            // 运费
            BigDecimal freightAmount = new BigDecimal(20);
            calcAmount.setFreightAmount(freightAmount);

            // 计算折扣：每满1000减200
            // 首先，计算总价可以被1000整除的次数（向下取整）
            // 然后，将这个次数乘以200，得到总的折扣额
            BigDecimal discount = price.divide(new BigDecimal("1000"), 0, BigDecimal.ROUND_DOWN).multiply(new BigDecimal("200"));
            calcAmount.setPromotionAmount(discount); // 设置优惠金额

            // 计算优惠后的总价：总价 - 折扣
            BigDecimal discountedTotal = price.subtract(discount);

            // 根据会员等级计算额外折扣
            BigDecimal discountRate = BigDecimal.ONE; // 默认不打折
            if (user.getStatus() == 1) { // 假设1表示会员等级一，享有九折
                discountRate = new BigDecimal("0.9");
            }
            if (user.getStatus() == 2) { // 假设2表示会员等级二，享有八折
                discountRate = new BigDecimal("0.8");
            }
            if (user.getStatus() == 3) { // 假设3表示会员等级三，享有七折
                discountRate = new BigDecimal("0.7");
            }
            if (user.getStatus() > 3) { // 更高级别会员享有六折
                discountRate = new BigDecimal("0.6");
            }

            // 应用会员折扣
            BigDecimal discountedPrice = discountedTotal.multiply(discountRate);
            // 计算实际支付金额：优惠后的总价 + 运费
            BigDecimal payAmount = discountedPrice.add(freightAmount);
            calcAmount.setPayAmount(payAmount); // 设置实际支付金额

            // 封装计算金额
            productGoodsResponse.setCalcAmount(calcAmount);

        }

        // 商品信息
        productGoodsResponse.setCartPromotionItemList(mallProductCarInfoResponses1);

        // 地址信息
        List<MallProductAddrInfo> mallProductAddrInfoList = mallProductInfoService.fetchAddressList();
        productGoodsResponse.setMemberReceiveAddressList(mallProductAddrInfoList);

        // 积分
        productGoodsResponse.setMemberIntegration(user.getIntegration());

        IntegrationConsumeSetting integrationConsumeSetting = new IntegrationConsumeSetting();
        integrationConsumeSetting.setCouponStatus(1);
        integrationConsumeSetting.setDeductionPerAmount(100);
        integrationConsumeSetting.setId(1);
        integrationConsumeSetting.setMaxPercentPerOrder(100);
        integrationConsumeSetting.setUseUnit(50);
        productGoodsResponse.setIntegrationConsumeSetting(integrationConsumeSetting);

        return productGoodsResponse;
    }

    @Override
    public void generateOrder(GenerateOrderRequest generateOrderRequest) {
        User user = getInfo();
        // 获取商品信息
        ProductGoodsResponse productGoodsResponse = generateConfirmOrder(generateOrderRequest.getCartIds());

        MallProductOrderInfo mallProductOrderInfo = new MallProductOrderInfo();
        // 用户ID
        mallProductOrderInfo.setUserId(user.getId());
//        mallProductOrderInfo.setUserId(2);
        // 地址ID
        mallProductOrderInfo.setAddressId(generateOrderRequest.getMemberReceiveAddressId());
        // 支付状态
        mallProductOrderInfo.setPayStatus("未支付");
        // 支付方式
        mallProductOrderInfo.setPayMethod("微信支付");
        // 计算积分可抵扣的金额
        BigDecimal integrationAmount = new BigDecimal(generateOrderRequest.getUseIntegration()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        mallProductOrderInfo.setUseIntegration(integrationAmount);
        // 支付金额
        mallProductOrderInfo.setPayAmount(productGoodsResponse.getCalcAmount().getPayAmount().subtract(integrationAmount));
        // 优惠金额
        mallProductOrderInfo.setPromotionAmount(productGoodsResponse.getCalcAmount().getPromotionAmount());
        // 订单金额
        mallProductOrderInfo.setTotalAmount(productGoodsResponse.getCalcAmount().getTotalAmount());
        mallProductGoodsInfoMapper.insert(mallProductOrderInfo);

    }


    /**
     * 获取用户信息
     */
    public User getInfo() {
        String token = redisTemplate.opsForValue().get("token");
        String cusUserJSONString = redisTemplate.opsForValue().get(token);
        User user = JSONObject.parseObject(cusUserJSONString, User.class);
        return user;
    }

}
